package com.lntea.netty.im.handler.server;

import com.lntea.netty.im.packet.*;
import com.lntea.netty.im.codec.PacketCodeC;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;

public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buffer = (ByteBuf) msg;

        // 数据包解码
        Packet packet = PacketCodeC.INSTANCE.decode(buffer);

        if (packet instanceof LoginRequestPacket) {
            LoginRequestPacket reqPacket = (LoginRequestPacket) packet;

            System.out.println(new Date() + String.format(": 用户%s开始登陆", reqPacket.getUserName()));
            LoginResponsePacket respPacket = new LoginResponsePacket();
            if (valid(reqPacket)) {
                // 校验通过
                respPacket.setSuccess(true);
                System.out.println(new Date() + String.format(": 用户%s登陆成功", reqPacket.getUserName()));
            } else {
                respPacket.setSuccess(false);
                respPacket.setReason("登录校验失败");
                System.out.println(new Date() + String.format(": 用户%s登陆失败，原因：%s",
                        reqPacket.getUserName(), respPacket.getReason()));
            }

            ByteBuf respBuffer = PacketCodeC.INSTANCE.encode(ctx.alloc(), respPacket);
            ctx.channel().writeAndFlush(respBuffer);
        } else if (packet instanceof MessageRequestPacket) {
            MessageRequestPacket reqPacket = (MessageRequestPacket) packet;
            System.out.println(new Date() + String.format(": 收到客户端消息：%s", reqPacket.getMessage()));

            MessageResponsePacket respPacket = new MessageResponsePacket();
            respPacket.setMessage("echo:" + reqPacket.getMessage());
            ByteBuf respBuffer = PacketCodeC.INSTANCE.encode(ctx.channel().alloc(), respPacket);
            ctx.channel().writeAndFlush(respBuffer);
        }
    }

    /**
     * 校验客户端登录
     * @param packet
     * @return
     */
    private boolean valid(LoginRequestPacket packet) {
        if (packet.getUserName().equals("admin") && packet.getPassword().equals("admin")) {
            return true;
        }
        return false;
    }
}
